#include "controal.h"
#include "iostream"
#include"NUC_communication.h"
#include "QThread"
controal::controal(QObject *parent) : QObject(parent)
{
        static QSerialPortInfo portInfo;

        auto a = portInfo.availablePorts();

        foreach (auto i, a) {
            qDebug() << i.portName() << endl;
        }

        port.setPort(a[0]);
        port.setBaudRate(1000000);
        port.setFlowControl(QSerialPort::NoFlowControl);
        port.setDataBits(QSerialPort::Data8);
        port.setStopBits(QSerialPort::OneStop);

        if(port.open(QIODevice::ReadWrite))
        {
            qDebug() << "open";
            connect(&port,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
        }
        else
        {
            qDebug() << "error";
            qDebug() << port.error();
        }

        toSTM32.shot = toSTM32.set_yaw = toSTM32.set_pitch =toSTM32.get = 0;
}
void controal::shout_Open(){
  //  std::cout<<"hello word"<<endl;
    toSTM32.shot=1;
    Send(toSTM32);
}
void controal::shout_Close(){
    toSTM32.shot=0;
    Send(toSTM32);
}
void controal::Set_Pitch_And_Yaw(float pitch, float yaw){
    toSTM32.set_pitch=pitch;
    toSTM32.set_yaw=yaw;
    Send(toSTM32);
}
void controal::shout(int num){
    toSTM32.shot=num;
    Send(toSTM32);
}
void controal::Send(NUC_data_t &toStm32){

    char data[64] = {};


    memcpy(data,&toStm32,sizeof(NUC_data_t));

    port.write(data,sizeof (NUC_data_t));
    bool pd = port.flush();

    qDebug()<<pd;

//    if(pd){

//         qDebug()<<"WriTEfail"<<endl;
//         getchar();
//    }

}

void controal::onReadyRead()
{
    qDebug()<<"GET"<<endl;
    QByteArray data = port.readAll();
    port.clear();
    unsigned char* ch = reinterpret_cast<unsigned char*>(data.data());
    memcpy(&formSTM32, ch, sizeof(STM32_data_t));
}
void  controal::get_Massage(){
    toSTM32.get=1;
    Send(toSTM32);
}
